<template>
  <div class="login">
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    ></van-nav-bar>

    <van-form @submit="onSubmit">
      <van-field
        v-model="form.phone"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          { validator: phoneCheck, message: '格式有误，请重新输入' },
         ]"
      ></van-field>
      <van-field
        v-model="form.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { validator: passwordCheck, message: '格式有误，请重新输入'},
        ]"
      ></van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" :loading="isLoading" loading-text="登录中...">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
  import { login } from '@/services/user'
  import { Toast } from 'vant'

  export default {
    name: 'Login',
    data() {
      return {
        form: {
          phone: '18201288771',
          password: '111111',
        },
        isLoading: false,
      }
    },
    methods: {
      phoneCheck(value) {
        return /^1\d{10}$/.test(value)
      },
      passwordCheck(value) {
        return /^[A-Za-z0-9]{6,12}$/.test(value)
      },
      async onSubmit() {
        this.isLoading = true
        const { state, content } = await login(this.form)
        if (state === 1) {
          Toast.success('登录成功')
          this.$store.commit('setUser', content)
          this.$router.push(this.$route.query.redirect || '/')
        } else {
          Toast.fail('登录失败')
        }
        this.isLoading = false
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
